package de.tyde.mylazysms;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.datatype.Duration;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class AppInfo extends Activity {
	DefaultHttpClient http_client = new DefaultHttpClient();
	final static String DB_NAME = "MyLazySMSDatabase";
	final static String TABLE_NAME = "MyLazySMSTable_User";
	SQLiteDatabase myDB = null;
	Account user;
	AccountManager accountManager = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		accountManager = AccountManager.get(this);
		System.out.println("AccountManager initialized");
		user = checkIfUserExist();
		if (user == null) {
			Intent intent = new Intent(this, AccountList.class);
			startActivityForResult(intent,Intent.FLAG_ACTIVITY_NEW_TASK);
		} else {

			setContentView(R.layout.app_info);
			
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		// Intent intent = getIntent();
		// AccountManager accountManager =
		// AccountManager.get(getApplicationContext());
		// Account account = (Account)intent.getExtras().get("account");
		// accountManager.getAuthToken(account, "ah", false, new
		// GetAuthTokenCallback(), null);
	}

	private Account checkIfUserExist() {
		myDB = this.openOrCreateDatabase(DB_NAME, MODE_PRIVATE, null);
		// Tabelle erstellen falls sie nicht existiert
		myDB.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME
				+ " (_id integer primary key autoincrement,"
				+ " user varchar(100),"
				+ " pw varchar(100));");
		Cursor c = myDB.rawQuery("SELECT _id, user, pw FROM " + TABLE_NAME + ";",
				null);
		startManagingCursor(c);
		c.moveToFirst();
		if (c.getCount() > 0) {
			Account[] accounts = accountManager.getAccountsByType("com.google");
			for (int x = 0; x < accounts.length; x++) {
				if(accounts[x].name.equals(c.getString(1))){
					return accounts[x];
				}
			}
		}
		return null;
	}

	private class GetAuthTokenCallback implements
			AccountManagerCallback<Bundle> {
		public void run(AccountManagerFuture<Bundle> result) {
			Bundle bundle;
			try {
				bundle = result.getResult();
				Intent intent = (Intent) bundle.get(AccountManager.KEY_INTENT);
				if (intent != null) {
					// User input required
					startActivity(intent);
				} else {
					onGetAuthToken(bundle);
				}
			} catch (OperationCanceledException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (AuthenticatorException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};

	protected void onGetAuthToken(Bundle bundle) {
		String auth_token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
		new GetCookieTask().execute(auth_token);
	}

	private class GetCookieTask extends AsyncTask<String, Void, Boolean> {
		protected Boolean doInBackground(String... tokens) {
			try {
				// Don't follow redirects
				http_client.getParams().setBooleanParameter(
						ClientPNames.HANDLE_REDIRECTS, false);

				HttpGet http_get = new HttpGet(
						"https://mylazysms.appspot.com/_ah/login?continue=http://localhost/&auth="
								+ tokens[0]);
				HttpResponse response;
				response = http_client.execute(http_get);
				if (response.getStatusLine().getStatusCode() != 302)
					// Response should be a redirect
					return false;

				for (Cookie cookie : http_client.getCookieStore().getCookies()) {
					if (cookie.getName().equals("ACSID"))
						return true;
				}
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				http_client.getParams().setBooleanParameter(
						ClientPNames.HANDLE_REDIRECTS, true);
			}
			return false;
		}

		protected void onPostExecute(Boolean result) {
			new AuthenticatedRequestTask()
					.execute("http://mylazysms.appspot.com/admin/");
		}
	}

	private class AuthenticatedRequestTask extends
			AsyncTask<String, Void, HttpResponse> {
		@Override
		protected HttpResponse doInBackground(String... urls) {
			try {
				HttpGet http_get = new HttpGet(urls[0]);
				return http_client.execute(http_get);
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

		protected void onPostExecute(HttpResponse result) {
			try {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(result.getEntity().getContent()));
				String first_line = reader.readLine();
				Toast.makeText(getApplicationContext(), first_line,
						Toast.LENGTH_LONG).show();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
